<?php
namespace app\index\controller;

use app\backend\model\Area;
use app\backend\model\LoginLog;
use app\backend\model\Photo;
use Business\sms\VComSms;
use think\Controller;
use app\backend\model\Member;
use Tools\Agent;
use Tools\Ip;

class IndexController extends Controller
{
    /**
     * 登录页面
     * @date   2016-1-3
     * @author Lanlc
     */
    public function index()
    {
        if ($this->checkLoginStatus()) {//已登录
            $userInfo = $this->getLoginInfo();
            $this->assign('nickname', $userInfo['nickname']);
            $this->assign('avatar', $userInfo['avatar']);
            $this->assign('dtype', $userInfo['p_dtype']);
            return $this->fetch('home');
        } else {//未登录
            return $this->fetch();
        }
    }
    /**
     * 登录页面
     * @date   2016-1-3
     * @author Lanlc
     */
    public function login()
    {
        if ($this->checkLoginStatus()) {//已登录
            $userInfo = $this->getLoginInfo();
            $this->assign('nickname', $userInfo['nickname']);
            $this->assign('avatar', $userInfo['avatar']);
            $this->assign('dtype', $userInfo['p_dtype']);
            return $this->fetch('home');
        } else {//未登录
            return $this->fetch();
        }
    }

    /**
     * 退出登录
     * @date   2017-02-07
     * @author Lanlc
     */
    public function logOut()
    {
        unset($_SESSION);
        session_destroy();
        $backUrl = config('login_url');
        $stript  = "<script>location.href='{$backUrl}';</script>";
        echo $stript;
        exit();
    }

    /**
     * 登录提交数据校验
     * @date   2017-05-09
     * @author wuhao
     *
     * @return json
     */
    public function login_action()
    {
        $type     = I('post.type', 1, 'intval');//登录类型 1=账号密码 2=手机号
        $memberModel = new Member();
        $photoModel  = new Photo();
        $refer = config('allow_url');
        $loginFlag = false;
        foreach ($refer as $val) {
            if (strpos($_SERVER['HTTP_REFERER'], $val)) {
                $loginFlag = true;
            }
        }
        if (!$loginFlag) {
            $this->apiReturn(202, [], '非法来源');
        }
        $MAX_ERROR_TIME = 5;
        $field = 'id, username, password, mobile, nickname, dtype, login_err_no, login_err_time';

        if ($type == 1) { //用户名密码登录
            $account  = I('post.username', '', 'strval');
            $password = I('post.password', '', 'strval');
            $code     = I('post.code', '', 'strval');
            if (!$account || !$password || !$code) {
                $this->apiReturn(400, [], '参数错误');
            }

            if (isset($_SESSION['auth_code'])) {
                if (strtolower($code) != strtolower($_SESSION['auth_code'])) {
                    $this->apiReturn(203, [], '验证码错误');
                }
            }


            $memberInfo = $memberModel->getMemberInfoByAccount($account, $field);
            if (!$memberInfo) {
                $this->apiReturn(201, [], '用户不存在');
            } else {
                //判断是否超过最大限制
                if ($memberInfo['login_err_no']>=$MAX_ERROR_TIME && (time()-strtotime($memberInfo['login_err_time']))<300) {
                    $this->apiReturn(204, [], "登录错误次数超过$MAX_ERROR_TIME"."次，5分钟内不可登录");
                }

                if ($memberInfo['password'] == $password) {
                    //注册session
                    $_SESSION['mid']      = $memberInfo['id'];
                    $_SESSION['username'] = $memberInfo['username'];
                    $_SESSION['mobile']   = $memberInfo['mobile'];
                    $_SESSION['nickname'] = $memberInfo['nickname'];
                    $_SESSION['dtype']    = $memberInfo['dtype'];
                    if ($memberInfo['dtype'] == 7) {//员工
                        //获取父账号信息
                        $parentId = $memberModel->getParentId($memberInfo['id']);
                        $parentInfo = $memberModel->getMemberInfoById($parentId['parent_id'], 'id, dtype');
                        $_SESSION['p_dtype'] = $parentInfo['dtype'];
                        $_SESSION['p_mid']   = $parentInfo['id'];
                    } else {
                        $_SESSION['p_dtype'] = $memberInfo['dtype'];
                        $_SESSION['p_mid']   = $memberInfo['id'];
                    }
                    $header = $photoModel->getPhoto(['rid' => $memberInfo['id'], 'rtype' => 4], 'url');
                    if ($header) {//头像
                        $_SESSION['avatar'] = $header[0]['url'];
                    } else {
                        $_SESSION['avatar'] = '';
                    }
                    //记录登录日志
                    $this->createLoginLog($memberInfo['id']);
                    //更新登陆错误次数和时间
                    $memberModel->updateUser($memberInfo['id'], ['login_err_no' => 0, 'login_err_time' => '0000-00-00 00:00:00']);
                    $this->apiReturn(200, ['dtype' => $_SESSION['dtype']], '登录成功');
                } else {
                    //更新登陆错误次数和时间
                    $memberModel->updateUser($memberInfo['id'], ['login_err_no' => $memberInfo['login_err_no']+1, 'login_err_time' => date('Y-m-d H:i:s')]);
                    $this->apiReturn(202, [], '账号或密码错误');
                }
            }
        } else { //手机号登录
            $mobile   = I('post.mobile', '', 'strval');
            $code     = I('post.code', '', 'strval');
            if (!$mobile || !$code) {
                $this->apiReturn(400, [], '参数错误');
            }
            $memberInfo = $memberModel->getMemberInfoByMobile($mobile, $field);
            if (!$memberInfo) {
                $this->apiReturn(201, [], '手机号尚未注册');
            } else {
                //判断是否超过最大限制
                if ($memberInfo['login_err_no']>=$MAX_ERROR_TIME && (time()-strtotime($memberInfo['login_err_time']))<300) {
                    $this->apiReturn(204, [], "登录错误次数超过$MAX_ERROR_TIME"."次，5分钟内不可登录");
                }
                //检查验证码
                $sms = new VComSms();
                $check = $sms->ChkVerifyCode($mobile, 'login', $code);
                if (!$check) {
                    //更新登陆错误次数和时间
                    $memberModel->updateUser($memberInfo['id'], ['login_err_no' => $memberInfo['login_err_no']+1, 'login_err_time' => date('Y-m-d H:i:s')]);
                    $this->apiReturn(403, [], '手机验证码错误');
                } elseif ($check === -1) {
                    $this->apiReturn(403, [], '验证码已经失效');
                } else {//验证通过
                    //注册session
                    $_SESSION['mid']      = $memberInfo['id'];
                    $_SESSION['username'] = $memberInfo['username'];
                    $_SESSION['mobile']   = $memberInfo['mobile'];
                    $_SESSION['nickname'] = $memberInfo['nickname'];
                    $_SESSION['dtype']    = $memberInfo['dtype'];
                    if ($memberInfo['dtype'] == 7) {//员工
                        //获取父账号信息
                        $parentId = $memberModel->getParentId($memberInfo['id']);
                        $parentInfo = $memberModel->getMemberInfoById($parentId['parent_id'], 'id, dtype');
                        $_SESSION['p_dtype'] = $parentInfo['dtype'];
                        $_SESSION['p_mid']   = $parentInfo['id'];
                    } else {
                        $_SESSION['p_dtype'] = $memberInfo['dtype'];
                        $_SESSION['p_mid']   = $memberInfo['id'];
                    }
                    $header = $photoModel->getPhoto(['rid' => $memberInfo['id'], 'rtype' => 4], 'url');
                    if ($header) {//头像
                        $_SESSION['avatar'] = $header[0]['url'];
                    } else {
                        $_SESSION['avatar'] = '';
                    }
                    //记录登录日志
                    $this->createLoginLog($memberInfo['id']);
                    //更新登陆错误次数和时间
                    $memberModel->updateUser($memberInfo['id'], ['login_err_no' => 0, 'login_err_time' => '0000-00-00 00:00:00']);
                    $this->apiReturn(200, ['dtype' => $_SESSION['dtype']], '登录成功');
                }
            }

        }

    }

    /**
     * 添加登录日志
     * @date   2017-04-28
     * @author wuhao
     *
     * @param int $mid  用户id
     * @return bool
     */
    public function createLoginLog($mid)
    {
        if (!$mid) {
            return false;
        }
        $loginIp       = get_client_ip();
        $loginIpInt    = ip2long($loginIp);
        $loginLocation = implode(" ", Ip::find($loginIp));
        $loginBrowser  = Agent::getBroswer();
        $loginOS       = Agent::getOs();
        $loginLogModel = new LoginLog();
        $res = $loginLogModel->createLoginLog($mid, $loginIpInt, $loginLocation, $loginBrowser, $loginOS);
        return $res ?: false;
    }

    /**
     * 获取省市区名称
     * @date   2016-01-18
     * @author Lanlc
     *
     * @return json
     */
    public function getAreaName()
    {
        $province = I('post.province', '', 'intval');
        $city     = I('post.city', '', 'intval');
        $country  = I('post.country', '', 'intval');

        $data = [$province, $city, $country];
        if (!$data) {
            $this->apiReturn(202, [], '缺少参数');
        }
        $areaModel = new Area();
        $res = $areaModel->getArea($data);

        if ($res) {
            $this->apiReturn(200, ['list' => $res], '');
        } else {
            $this->apiReturn(201, [], '系统错误，请稍后重试');
        }
    }

    /**
     * 获取省份信息
     * @date   2016-1-9
     * @author Lanlc
     *
     * @return json
     */
    public function getProvince()
    {
        $areaModel = new Area();
        $res = $areaModel->getArea(0);
        if ($res) {
            $this->apiReturn(200, ['list' => $res], '');
        } else {
            $this->apiReturn(201, [], '系统错误，请稍后重试');
        }
    }

    /**
     * 获取城市信息
     * @date   2016-1-9
     * @author Lanlc
     *
     * @return json
     */
    public function getCity()
    {
        $provinceId = I('post.province_id', 0, 'intval');
        if (!$provinceId) {
            $this->apiReturn(400, [], '参数错误');
        }
        $areaModel = new Area();
        $res = $areaModel->getArea($provinceId);
        if ($res) {
            $this->apiReturn(200, ['list' => $res], '');
        } else {
            $this->apiReturn(201, [], '系统错误，请稍后重试');
        }
    }

    /**
     * 获取区县信息
     * @date   2016-1-9
     * @author Lanlc
     *
     * @return json
     */
    public function getCountry()
    {
        $cityId = I('post.city_id', 0, 'intval');
        if (!$cityId) {
            $this->apiReturn(400, [], '参数错误');
        }

        $areaModel = new Area();
        $res = $areaModel->getArea($cityId);
        if ($res) {
            $this->apiReturn(200, ['list' => $res], '');
        } else {
            $this->apiReturn(201, [], '没有相关数据');
        }
    }

    /**
     * 获取区县信息后端调用
     * @date   2017-3-8
     * @author wuhao
     *
     * @param int $cityId 城市id
     * @return array|bool
     */
    public function getCountrys($cityId)
    {
        if (!$cityId) {
            return false;
        }

        $areaModel = new Area();
        $res = $areaModel->getArea($cityId);
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * 个人中心
     * @date   2016-1-6
     * @author WangTong
     */
    public function home()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [0, 1, 2, 3, 4, 5, 6])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        $this->assign('avatar', $userInfo['avatar']);
        return $this->fetch();
    }


    /**
     * 个人中心
     * @date   2016-1-3
     * @author Lanlc
     */
    public function usercenter()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']); //父账号dtype
        $this->assign('sdtype', $userInfo['dtype']);  //自己的dtype
        return $this->fetch();
    }

    /**
     * 用户管理
     * @date   2016-1-3
     * @author Lanlc
     */
    public function user()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [0, 1, 3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);

        return $this->fetch();
    }

    /**
     * 房源管理
     * @date   2016-1-3
     * @author Lanlc
     */
    public function house()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);//传父账号dtype
        return $this->fetch();
    }


      /**
     * 楼宇管理
     * @date   2017-03-13
     * @author WT
     */
    public function building()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 收入管理
     * @date   2017-03-24
     * @author WT
     */
    public function income()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 3, 4, 5, 6])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch('income');
    }

    /**
     * 租赁合约
     * @date   2016-1-3
     * @author Lanlc
     */
    public function lease()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 2, 3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 应付账单
     * @date   2016-1-3
     * @author Lanlc
     */
    public function lease_pay()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [2])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 应收账单
     * @date   2016-1-3
     * @author Lanlc
     */
    public function lease_income()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 3, 4, 5, 6])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 应收账单-托管账号登陆
     * @date   2016-1-3
     * @author Lanlc
     */
    public function trust_income()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 支付页面
     * @date   2016-1-10
     * @author WangTOng
     */
    public function pay()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [0, 1, 2, 3, 4, 5, 6])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 托管结算
     * @date   2016-1-10
     * @author
     */
    public function trust()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [1, 3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 托管结算 - 新增
     * @date   2016-1-10
     * @author
     */
    public function trust_add()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }


    /**
     * 托管应付
     * @date   2016-1-19
     * @author
     */

    public function trust_pay()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }


    /**
     * 租赁签约 - 新增
     * @date   2016-1-19
     * @author
     */
    public function lease_add()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 注册
     */
    public function register()
    {
        return view();
    }

    /**
     * 消息管理
     * @date   2016-1-19
     * @author WangTong
     */
    public function notice()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [0])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 提现申请列表
     * @date   2017-5-10
     * @author wuhao
     */
    public function wdlist()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
     /**
     * 用户信息
     * @date   2017-5-26
     * @author wuhao
     */
    public function userinfo()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 交易记录
     * @date   2017-5-26
     * @author wuhao
     */
    public function trade_record()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
      /**
     * 费用审批
     * @date   2017-6-1
     * @author wuhao
     */
    public function fee_approve()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
      /**
     * 物业水电管理
     * @date   2017-6-1
     * @author wuhao
     */
    public function prop_management()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
     /**
     * 浏览器版本页面
     * @date   2017-6-6
     * @author wuhao
     */
    public function browser()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 文件处理结果页面
     * @date   2017-6-7
     * @author wuhao
     */
    public function file_result()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 文件打印页面
     * @date   2017-6-12
     * @author wuhao
     */
    public function print_file()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 消息日志管理页面
     * @date   2017-6-12
     * @author wuhao
     */
    public function msgs_log()
    {
        $userInfo = $this->getLoginInfo();
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 合约完善
     * @date   2017-6-27
     * @author wuhao
     */
    public function lease_fix()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 对账文件管理
     * @date   2017-7-17
     * @author wuhao
     */
    public function bill_check_management()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }
    /**
     * 对账结果
     * @date   2017-7-17
     * @author wuhao
     */
    public function bill_check_result()
    {
        $userInfo = $this->getLoginInfo();
//        if (!in_array($userInfo['p_dtype'], [3, 4])) {
//            exit('无权操作');
//        }
        $this->assign('dtype', $userInfo['p_dtype']);
        return $this->fetch();
    }

    /**
     * 获取权限
     */
    public function getPower()
    {
        $userInfo = $this->getLoginInfo();
        $all = require_once(APP_PATH.'Conf/menu.conf.php');
        if ($userInfo['dtype'] != 7) {
            $auth = load_config($userInfo['dtype'], 'auth');
            $default = 26; //默认房源管理
        } else {
            $memberModel = new Member();
            $auth = $memberModel->getMemberInfoById($userInfo['mid'], 'member_auth');
            $auth = json_decode($auth['member_auth'], true);
            if (!$auth) {
                $default = -1;  //没有任何权限
                $this->apiReturn(201, ['default' => $default], '');
            }

            if (in_array(26, $auth)) { //员工如果有权限访问房源的话就访问房源
                $default = 26;
            } else {  //否则访问二级菜单的其中一个
                $default = -1;
                $second = [];
                foreach ($all as $v) {
                    if ($v['type'] == 2) {
                        $second[] = $v['id'];
                    }
                }
                foreach ($auth as $value) {
                    if (in_array($value, $second)) {
                        $default = $value;
                        break;
                    }
                }
            }
        }

        $authDetail = [];
        foreach ($all as $v) {
            foreach ($auth as $value) {
                if ($value == $v['id']) {
                    $authDetail[] = $v;
                    break;
                }
            }
        }

        $data = [
            'menu' => $authDetail,
            'default' => $default,
        ];
        if ($default == -1) {
            $this->apiReturn(201, ['default' => $default], '');
        } else {
            $this->apiReturn(200, $data, '');
        }

    }

}
